/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.kamai.persistence.dao;

import com.edu.kamai.persistence.beans.Score;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author xyzhu
 */
public class ScoreDao {
    private static final Log log = LogFactory.getLog(Score.class);
    public static final String PAPER_BEAN = "com.edu.kamai.persistence.beans.Score";
    private Session session = null;
    
    public ScoreDao(){
        this.session  = kamaiHibernateUtil.getSessionFactory().openSession();
    }
    
    public void addScore(Score score){
        log.debug("save score instance");
        try{
            Transaction tx = session.beginTransaction();
            session.save(score);
            tx.commit();
            log.debug("save successful");
            
        }catch(RuntimeException re){
            log.error("save failed", re);
            throw re;
        }
    }
    
    public Score getScoreByContestIDAndUserID(int cID,String uID){
        log.debug("check score record " + cID + ":" + uID);
        try{
            Transaction tx = session.beginTransaction();
            String hqlStr=new String("from Score where student_id='" + uID +
                        "' and contest_id=" +  cID);
            //System.out.println(hqlStr);
            List<Score> list = session.createQuery(hqlStr).list();
            tx.commit();
            return list.size() == 0 ? null : list.get(0);
            
        }catch(Exception e){
            log.error("check login failed", e);
            return null;
        }
    }
    
    public List<Score> getScoreByUserID(String uID){
        log.debug("check score record :" + uID);
        try{
            Transaction tx = session.beginTransaction();
            String hqlStr=new String("from Score where student_id='" + uID +"'");
            //System.out.println(hqlStr);
            List<Score> list = session.createQuery(hqlStr).list();
            tx.commit();
            return list;
            
        }catch(Exception e){
            log.error("check login failed", e);
            return null;
        }
    }
    
    public void updateScore(Score score){
        log.debug("update score instance");
        try{
            Transaction tx = session.beginTransaction();
            session.update(score);
            tx.commit();
            log.debug("update successful");
            
        }catch(RuntimeException re){
            log.error("update failed",re);
            throw re;
        }
    }
    
    
    
}
